package com.example.demo.service.Impl;

import com.example.demo.entity.PageBean;
import com.example.demo.entity.Result;
import com.example.demo.entity.Student;
import com.example.demo.entity.StudentQueryParam;
import com.example.demo.exception.CustomException;
import com.example.demo.mapper.StudentMapper;
import com.example.demo.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 分页查询
     * @param param
     * @return
     */
    @Override
    public PageBean page(StudentQueryParam param) {
        //1. 设置分页参数
        PageHelper.startPage(param.getPage(),param.getPageSize());
        List<Student> studentList = studentMapper.getPage(param);
        Page<Student> p = (Page) studentList;
        return new PageBean(p.getTotal(),p.getResult());
    }

    /**
     * 新增学生
     * @param student
     */
    @Override
    public void save(Student student) {
        //1. 补充基础数据
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        student.setViolationCount((short) 0);
        student.setViolationScore((short) 0);
        studentMapper.insert(student);
    }

    /**
     * 根据id查询学生
     * @param id
     * @return
     */
    @Override
    public Student getById(Integer id) {
        return studentMapper.getById(id);
    }

    /**
     * 修改学生信息
     * @param student
     */
    @Override
    public void update(Student student) {
        //1. 补充基础数据
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    /**
     * 批量删除学生
     * @param ids
     */
    @Override
    public void delete(List<Integer> ids) {
        studentMapper.delete(ids);
    }

    /**
     * 扣分处理
     * @param id
     * @param score
     */
    @Override
    public void violationHandle(Integer id, Short score) {
        //1. 判断分数是否合法,传过来的必须是数字
        if(score <= 0 ){
            throw new CustomException(Result.error("扣分分数不合法"));
        }else {
            //2. 获取学生信息
            Student student = studentMapper.getById(id);
            student.setViolationCount((short) (student.getViolationCount()+1));
            student.setViolationScore((short) (student.getViolationScore()+score));
            studentMapper.update(student);
        }
    }
}
